﻿global using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components.Authorization;

using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
namespace Jwt.Client;

internal class ApiAuthenticationStateProvider : AuthenticationStateProvider
{
    private static readonly Task<AuthenticationState> DefaultUnauthenticatedTask = Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));

    private Task<AuthenticationState> _authenticationStateTask = DefaultUnauthenticatedTask;

    private readonly ILocalStorageService _localStorageService;
    private readonly HttpClient _httpClient;
    public ApiAuthenticationStateProvider(ILocalStorageService localStorageService, HttpClient httpClient)
    {
        _localStorageService = localStorageService;
        _httpClient = httpClient;
        SetState();

    }
    public override Task<AuthenticationState> GetAuthenticationStateAsync() => _authenticationStateTask;

    public void SetUserStatus()
    {
        SetState();
        NotifyAuthenticationStateChanged(_authenticationStateTask);
    }
    private void SetState()
    {
        var savedToken = _localStorageService.GetItem<string>("JwtToken");
        if (string.IsNullOrEmpty(savedToken))
        {
            _authenticationStateTask = DefaultUnauthenticatedTask;
            return;
        }


        var h = new JwtSecurityTokenHandler();
        var payload = h.ReadJwtToken(savedToken).Payload;
        var claims = payload.Claims;
        var exp = claims.First(ii => ii.Type == "exp").Value;
        var dt = DateTimeOffset.FromUnixTimeSeconds(int.Parse(exp)).LocalDateTime;
        if (dt < DateTimeOffset.Now)
        {
            _authenticationStateTask = DefaultUnauthenticatedTask;
            return;
        }
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", savedToken);
        _authenticationStateTask = Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"))));

    }

}
